"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _wechaty = require("wechaty");

var _login = _interopRequireDefault(require("./event-operator/login"));

var _loginout = _interopRequireDefault(require("./event-operator/loginout"));

var _scan = _interopRequireDefault(require("./event-operator/scan"));

var _logger = _interopRequireDefault(require("./logger"));

// const WECHATY_PUPPET_PADCHAT_TOKEN = 'your-token-here'
// const puppet = 'wechaty-puppet-padchat'
// const puppetOptions = {
//   token: 'WECHATY_PUPPET_PADCHAT_TOKEN',
// }
var WechatyManager =
/*#__PURE__*/
function () {
  function WechatyManager() {
    var _this = this;

    (0, _classCallCheck2.default)(this, WechatyManager);
    (0, _defineProperty2.default)(this, "onMessage",
    /*#__PURE__*/
    function () {
      var _ref = (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee(message) {
        var contact, text, msgRoom, index, findRooms;
        return _regenerator.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _logger.default.debug('receive message from %s, message type %s, message.text %s', message.from().name(), message.type(), message.text());

                if (!(message.type() === _wechaty.Message.Type.Text)) {
                  _context.next = 21;
                  break;
                }

                contact = message.from();
                text = message.text();
                msgRoom = message.room();

                if (!(!msgRoom && contact.id !== _this.bot.userSelf().id)) {
                  _context.next = 21;
                  break;
                }

                index = _this.getContactIndex(contact);

                if (!(index !== -1)) {
                  _context.next = 12;
                  break;
                }

                _this.tempJoinRoomContacts.splice(index, 1);

                if (!(_this.tempJoinRoomContacts[index].rooms && _this.tempJoinRoomContacts[index].rooms[text])) {
                  _context.next = 12;
                  break;
                }

                _this.addContactInRoom(contact, _this.tempJoinRoomContacts[index].rooms[text]);

                return _context.abrupt("return");

              case 12:
                _context.next = 14;
                return _this.bot.Room.findAll({
                  topic: text
                });

              case 14:
                findRooms = _context.sent;

                if (!(findRooms.length === 0)) {
                  _context.next = 19;
                  break;
                }

                _context.next = 18;
                return _this.bot.Room.findAll({
                  topic: new RegExp("^.*".concat(text, ".*$"))
                });

              case 18:
                findRooms = _context.sent;

              case 19:
                _logger.default.info('%s find rooms: %s', text, JSON.stringify(findRooms));

                _this.addContactInRooms(contact, findRooms);

              case 21:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }());
    (0, _defineProperty2.default)(this, "onFriend", function (friendship) {
      if (friendship.type() === _wechaty.Friendship.Type.Receive) {
        friendship.accept();
      }
    });
    (0, _defineProperty2.default)(this, "onRoomInvitation",
    /*#__PURE__*/
    function () {
      var _ref2 = (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee2(roomInvitation) {
        return _regenerator.default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.prev = 0;

                _logger.default.info("received room-invite event.");

                _context2.next = 4;
                return roomInvitation.accept();

              case 4:
                _context2.next = 9;
                break;

              case 6:
                _context2.prev = 6;
                _context2.t0 = _context2["catch"](0);

                _logger.default.error("join room failed %s", _context2.t0);

              case 9:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this, [[0, 6]]);
      }));

      return function (_x2) {
        return _ref2.apply(this, arguments);
      };
    }());
    (0, _defineProperty2.default)(this, "startBot",
    /*#__PURE__*/
    (0, _asyncToGenerator2.default)(
    /*#__PURE__*/
    _regenerator.default.mark(function _callee3() {
      return _regenerator.default.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _logger.default.info('start bot begin');

              _this.bot.on('scan', _scan.default);

              _this.bot.on('login', function (user) {
                _logger.default.info('%s login success', user);

                _this.login = true;
                (0, _login.default)(user);
              });

              _this.bot.on('logout', function (user) {
                _logger.default.info('%s logout success', user);

                _this.login = false;
                (0, _loginout.default)(user);
              });

              _this.bot.on('message', _this.onMessage);

              _this.bot.on('friendship', _this.onFriend);

              _this.bot.on('room-invite', _this.onRoomInvitation);

              _context3.next = 9;
              return _this.bot.start();

            case 9:
              _logger.default.info('start bot end');

            case 10:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, this);
    })));
    this.bot = new _wechaty.Wechaty({
      profile: 'wechatyName'
    });
    this.login = false;
    this.tempJoinRoomContacts = [];
    this.robotOwner = null;
  }

  (0, _createClass2.default)(WechatyManager, [{
    key: "getContactIndex",
    value: function getContactIndex(contact) {
      return this.tempJoinRoomContacts.findIndex(function (item) {
        return item.id === contact.id;
      });
    }
  }, {
    key: "addContactInRooms",
    value: function () {
      var _addContactInRooms = (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee4(contact, rooms) {
        var message, i, topic, owner, ownerName;
        return _regenerator.default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                if (!(!rooms || !rooms.length)) {
                  _context4.next = 3;
                  break;
                }

                contact.say('can not find room');
                return _context4.abrupt("return");

              case 3:
                if (!(rooms.length === 1)) {
                  _context4.next = 6;
                  break;
                }

                this.addContactInRoom(contact, rooms[0]);
                return _context4.abrupt("return");

              case 6:
                message = '请选择：<br/>';
                i = 0;

              case 8:
                if (!(i < rooms.length)) {
                  _context4.next = 20;
                  break;
                }

                _context4.next = 11;
                return rooms[i].topic();

              case 11:
                topic = _context4.sent;
                _context4.next = 14;
                return rooms[i].owner();

              case 14:
                owner = _context4.sent;
                ownerName = owner && owner.name;
                message += "".concat(i + 1, ": \u7FA4\u540D\u79F0: ").concat(topic, "; ").concat(ownerName && "\u7FA4\u4E3B: ".concat(ownerName), "<br/>");

              case 17:
                ++i;
                _context4.next = 8;
                break;

              case 20:
                contact.say(message);
                this.recordTempContact(contact, rooms);

              case 22:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      return function addContactInRooms(_x3, _x4) {
        return _addContactInRooms.apply(this, arguments);
      };
    }()
  }, {
    key: "recordTempContact",
    value: function recordTempContact(contact, rooms) {
      var _this2 = this;

      var index = this.getContactIndex(contact);

      if (index !== -1) {
        this.tempJoinRoomContacts[index] = {
          contact: contact,
          rooms: rooms
        };
      }

      setTimeout(function () {
        var index = _this2.getContactIndex(contact);

        if (index !== -1) {
          _this2.tempJoinRoomContacts.splice(index, 1);
        }
      }, 1000 * 60);
    }
  }, {
    key: "addContactInRoom",
    value: function () {
      var _addContactInRoom = (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee5(contact, room) {
        var memberList;
        return _regenerator.default.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                _context5.next = 2;
                return room.memberList();

              case 2:
                memberList = _context5.sent;

                if (!(memberList.length === 500)) {
                  _context5.next = 8;
                  break;
                }

                contact.say('is full');
                room.say("@".concat(room.owner().name(), ", group is full, some people can't join"));
                _context5.next = 20;
                break;

              case 8:
                if (!memberList.find(function (item) {
                  return item.id === contact.id;
                })) {
                  _context5.next = 11;
                  break;
                }

                contact.say('you has in the group');
                return _context5.abrupt("return");

              case 11:
                _context5.prev = 11;
                _context5.next = 14;
                return room.add(contact);

              case 14:
                _context5.next = 19;
                break;

              case 16:
                _context5.prev = 16;
                _context5.t0 = _context5["catch"](11);
                console.error(_context5.t0);

              case 19:
                room.say("@".concat(contact.name(), ", welcome join in"));

              case 20:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this, [[11, 16]]);
      }));

      return function addContactInRoom(_x5, _x6) {
        return _addContactInRoom.apply(this, arguments);
      };
    }()
  }, {
    key: "findRooms",
    value: function () {
      var _findRooms = (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee6(topic) {
        return _regenerator.default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                if (this.login) {
                  _context6.next = 3;
                  break;
                }

                _context6.next = 3;
                return this.startBot();

              case 3:
                return _context6.abrupt("return", this.bot.Room.findAll(topic ? {
                  topic: topic
                } : null));

              case 4:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));

      return function findRooms(_x7) {
        return _findRooms.apply(this, arguments);
      };
    }()
  }, {
    key: "findContactFriends",
    value: function () {
      var _findContactFriends = (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee7(query) {
        return _regenerator.default.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                if (this.login) {
                  _context7.next = 3;
                  break;
                }

                _context7.next = 3;
                return this.startBot();

              case 3:
                return _context7.abrupt("return", this.bot.Contact.findAll(query));

              case 4:
              case "end":
                return _context7.stop();
            }
          }
        }, _callee7, this);
      }));

      return function findContactFriends(_x8) {
        return _findContactFriends.apply(this, arguments);
      };
    }()
  }, {
    key: "saySelf",
    value: function () {
      var _saySelf = (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee8(text) {
        return _regenerator.default.wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                if (this.login) {
                  _context8.next = 3;
                  break;
                }

                _context8.next = 3;
                return this.startBot();

              case 3:
                this.bot.userSelf().say(text);

              case 4:
              case "end":
                return _context8.stop();
            }
          }
        }, _callee8, this);
      }));

      return function saySelf(_x9) {
        return _saySelf.apply(this, arguments);
      };
    }()
  }, {
    key: "sayRobotOwner",
    value: function () {
      var _sayRobotOwner = (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee9(text) {
        return _regenerator.default.wrap(function _callee9$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                _context9.prev = 0;

                if (this.login) {
                  _context9.next = 4;
                  break;
                }

                _context9.next = 4;
                return this.startBot();

              case 4:
                _logger.default.info('sat owner 111');

                if (this.robotOwner) {
                  _context9.next = 9;
                  break;
                }

                _context9.next = 8;
                return this.bot.Contact().find({
                  alias: "呃呃",
                  name: 'owner'
                });

              case 8:
                this.robotOwner = _context9.sent;

              case 9:
                console.log(this.robotOwner);

                _logger.default.info('sat owner 333');

                _context9.next = 13;
                return this.robotOwner.say(text);

              case 13:
                _logger.default.info('sat owner 222');

                _context9.next = 19;
                break;

              case 16:
                _context9.prev = 16;
                _context9.t0 = _context9["catch"](0);

                _logger.default.info('sat owner err %s', err);

              case 19:
              case "end":
                return _context9.stop();
            }
          }
        }, _callee9, this, [[0, 16]]);
      }));

      return function sayRobotOwner(_x10) {
        return _sayRobotOwner.apply(this, arguments);
      };
    }()
  }]);
  return WechatyManager;
}();

exports.default = WechatyManager;